package Tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 前序遍历
 */
public class preorderTraversal {
    /**
     * 递归遍历
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        preorder(root, list);
        return list;
    }

    public void preorder(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        preorder(root.left, list);
        preorder(root.right, list);
    }

    /**
     * 迭代遍历
     */
    public List<Integer> preorderTraversal2(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);     //中
            if (node.right != null) {
                stack.push(node.right); //右
            }
            if (node.left != null) {
                stack.push(node.left);//左
            }
        }
        return list;
    }

    /**
     * 统一迭代遍历
     * 右左中-->中左右
     */
    public List<Integer> preorderTraversal3(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            if (cur != null) {
                TreeNode node = stack.pop();
                if (node.right != null) {
                    stack.push(node.right);//右
                }
                if (node.left != null) {
                    stack.push(node.left);//左
                }
                stack.push(node);//中
                stack.push(null);
            } else {
                stack.pop();
                list.add(stack.pop().val);
            }
        }
        return list;
    }


}
